package Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:利用链表来实现队列，我们根据让它尾入队，头出队
 * User: 石方旭
 * Date: 2022-05-12
 * Time: 14:46
 */
class Node {
    public int val;//节点的值
    public Node next;//下一个节点的地址
    public Node(int val){
        this.val = val;
    }

}
public class MyQueue {

    private Node front;
    private Node rear;
    private int usedSize;
    /**
     * 入队 ---->使用尾入队
     * @param val
     * @return
     */
    public Boolean offer(int val){
        Node node = new Node(val);
        if(front==null){
            front = node;
            rear = node;
        }else {
            rear.next = node;
            rear=node;
        }
        this.usedSize++;
        return true;
    }

    /**
     * 使用头删来删除队头
     * @return
     */
    public int poll(){
        if(isEmpty()){
            throw new RuntimeException("队列为空！！！");
        }
        //1 2
        int val = front.val;
        front = front.next;
        if(front==null){
            rear=null;
        }
        this.usedSize--;
        return val;
    }

    public int peek(){
        if(isEmpty()){
            throw new RuntimeException("队列为空！！！");
        }
         return front.val;
    }

    public int size(){
        return this.usedSize;
    }

    public Boolean isEmpty(){
        return this.usedSize==0;
    }

    public void display(){
        Node cur = front;
        while(front!=null){
            System.out.print(front.val+" ");
            front=front.next;
        }
        System.out.println();
    }

}
